<template>
  <el-dialog :title="title" :visible.sync="visible" width="600px" append-to-body :destroy-on-close="true">
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="被评价部门" prop="evaluatedName" v-if="form.type == 5">
        <el-cascader
          v-model="form.evaluated"
          :options="dataList"
          :props="defaultProps"
          :clearable="true"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="被评价人" prop="evaluatedName" v-if="form.type == 6">
        <el-tag closable @close="evaluatedTagClose()" v-if="form.evaluatedName">
          {{ form.evaluatedName }}
        </el-tag>
        <el-button
          @click="addEvaluatedTag"
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-plus"
          circle
        ></el-button>
      </el-form-item>
      <el-form-item label="评价人" prop="evaluators">
        <el-tag
          class="tag-click"
          v-for="e in form.evaluators"
          :key="e.id"
          closable
          @close="tagClose(e)"
          @click="handleTagClick(e)"
        >
          {{
            form.evaluators.filter((f) => f.name === e.name).length > 1
              ? e.name + '(' + e.orgName + ')' + (e.userRelationName ? '-' + e.userRelationName : '')
              : e.name + (e.userRelationName ? '-' + e.userRelationName : '')
          }}
        </el-tag>
        <el-button @click="addTag" style="margin-left: 10px" type="primary" icon="el-icon-plus" circle></el-button>
        <el-button size="mini" type="text" icon="el-icon-delete" @click="clearTag" style="margin-left: 10px"
          >清空
        </el-button>
      </el-form-item>
      <!--            <el-form-item label="人事关系" prop="name" v-if="form.type == 6">
                            <el-select v-model="form.selectedList"  placeholder="请选择">
                                <el-option v-for="item in userRelationList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>-->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <user-select-dialog ref="evaluatedSelect" @ok="handleEvaluatedSelect"></user-select-dialog>
    <user-select-dialog ref="userSelect" @ok="handleOk"></user-select-dialog>
    <user-relation-modal ref="userRelationModal" @ok="handleTagOK"></user-relation-modal>
  </el-dialog>
</template>

<script>
import { getRequest, postRequest } from '@/api/baseRequest'
import UserSelectDialog from '@/views/manage/org/UserSelectDialog.vue'
import { listRelation } from '@/api/project/user-relation'
import UserRelationModal from '@/views/form/relationship/UserRelationModal.vue'

export default {
  name: 'RelationshipModal',
  components: { UserSelectDialog, UserRelationModal },
  data() {
    return {
      title: '操作',
      buttonStyle: 'solid',
      // 按钮loading
      buttonLoading: false,
      visible: false,
      userRelationList: [],
      form: {
        evaluators: [],
        formKey: '',
        type: '',
        evaluatedName: ''
      },
      url: {
        list: '/org/tree',
        add: '/form/relationship/addRelationShip',
        update: '/form/relationship/updateRelationShip'
      },
      dataList: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        checkStrictly: true,
        value: 'id'
      },
      selectedUserIds: [],
      selectedUserRows: [],
      isEdit: true
    }
  },
  created() {
    this.getTreeList()
    // this.getUserRelationList()
    // this.form.formKey = this.$route.query.key || this.$route.params.key
  },
  filters: {},
  methods: {
    handleTagOK(form) {
      console.log(form)
      console.log(this.form.evaluators)
      for (let e of this.form.evaluators) {
        if (e.id == form.id) {
          e.userRelationId = form.selectedList
          e.userRelationName = form.userRelationName
          break
        }
      }
    },
    handleTagClick(e) {
      console.log(e)
      if (this.form.type != 6) {
        return
      }
      this.$refs.userRelationModal.form.id = e.id
      this.$refs.userRelationModal.form.formKey = this.form.formKey
      this.$refs.userRelationModal.form.selectedList = e.userRelationId
      this.$refs.userRelationModal.form.evaluated = this.form.evaluated
      this.$refs.userRelationModal.update()
    },
    // 表单重置
    reset() {
      this.form.evaluators = []
      this.form.evaluated = undefined
      this.form.evaluatedName = ''
      this.resetForm('form')
    },
    add() {
      this.visible = true
      this.isEdit = false
      this.reset()
      console.log(this.form)
      // this.getUserRelationList()
    },
    edit(record) {
      this.isEdit = true
      this.visible = true
      // this.getUserRelationList()
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.form = Object.assign({}, record)
        console.log(this.form)
      })
    },
    cancel() {
      this.reset()
      this.visible = false
    },
    submitForm() {
      this.buttonLoading = true
      let evaluated = this.form.evaluated
      if (typeof evaluated === 'object') {
        this.form.evaluated = evaluated[evaluated.length - 1]
      }
      let url = this.isEdit ? this.url.update : this.url.add
      postRequest(url, this.form)
        .then((res) => {
          if (res.code === 200) {
            this.$emit('ok')
            this.visible = false
          }
        })
        .finally((r) => {
          this.buttonLoading = false
        })
    },
    getTreeList() {
      let param = { withSelf: 'WITHOUT_SELF' }
      getRequest(this.url.list, param).then((response) => {
        console.log(response)
        this.dataList = response.data
      })
    },
    tagClose(e) {
      for (let i = 0; i < this.form.evaluators.length; i++) {
        if (this.form.evaluators[i].id === e.id) {
          this.$delete(this.form.evaluators, i)
        }
      }
    },
    evaluatedTagClose() {
      this.form.evaluatedName = ''
      this.form.evaluated = ''
    },
    addTag() {
      this.$refs.userSelect.visible = true
    },
    addEvaluatedTag() {
      this.$refs.evaluatedSelect.visible = true
    },
    clearTag() {
      this.form.evaluators = []
    },
    handleOk(ids, rows) {
      this.selectedUserIds = ids
      this.selectedUserRows = rows
      let evaluators = this.selectedUserRows.map((r) => {
        return {
          id: r.id,
          name: r.name,
          orgName: r.orgName
        }
      })
      this.form.evaluators = [...this.form.evaluators, ...evaluators]
      if (this.form.evaluators.length > 1) {
        const map = this.form.evaluators.map((ev) => ev.id)
        this.form.evaluators = this.form.evaluators.filter((item, index) => {
          return map.indexOf(item.id) === index
        })
      }
    },
    handleEvaluatedSelect(ids, rows) {
      if (ids.length > 1 || rows.length > 1) {
        this.$message.warning('被评价人只能选择一个')
        return
      }
      this.form.evaluated = ids[0]
      this.form.evaluatedName = rows[0].name
    }
  }
}
</script>

<style scoped>
.tag-click {
  cursor: pointer;
}
</style>
